package com.cross.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.cross.sax.StringReplacer;

public class FileUtil {

	/**
	 * 复制文件
	 * 
	 * 2009-1-20
	 * 
	 * @author craziness_stone
	 * @param src
	 * @param dest
	 */
	public static void copy(File src, File dest){
		if (src == dest || src == null || dest == null) {
			return;
		}
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(src);
			os = new FileOutputStream(dest);
			byte[] b = new byte[1000];
			int length = 0;
			while ((length = is.read(b)) != -1) {
				os.write(b, 0, length);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != is) {
					is.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (null != os) {
					os.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void replace(File file, String soucre, String dest){
		StringReplacer replacer = new StringReplacer(soucre, dest);
		replace(file, replacer);
	}
	
	public static void replace(File file, StringReplacer replacer){
		try {
			FileInputStream inputStream = new FileInputStream(file);
			File f = File.createTempFile("temp", "txt");
			OutputStream outputStream = new FileOutputStream(f);
			byte[] buffer = new byte[8096];
			int count = -1;
			byte[] temp = null;
			try {
				while ((count = inputStream.read(buffer)) != -1) {
					temp = replacer.replace(buffer, 0, count);
					outputStream.write(temp, 0, temp.length);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			copy(f, file);
		} catch (FileNotFoundException e2) {
			e2.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		File f = new File("d:/aaa.txt");
		StringReplacer replacer = new StringReplacer("\r\n","&nbsp;");
		replace(f, replacer);
	}
}
